import { Component, OnInit, ViewChild, TemplateRef} from '@angular/core';
import {Observable} from 'rxjs';
import {
  CalendarEvent,
  CalendarEventAction,
  CalendarEventTimesChangedEvent,
  CalendarView
} from 'angular-calendar';
import {map, switchMap} from 'rxjs/operators';
import * as fromRoot from '../../reducers';
import {Store, select} from '@ngrx/store';
import {ActivatedRoute} from '@angular/router';
import { TaskService } from 'src/app/services/task.service';
import {startOfDay, endOfDay, isSameDay, isSameMonth} from 'date-fns';
const colors: any = {
   red: {
     primary: '#ad2121',
     secondary: '#fae3e3'
   },
   blue: {
     primary: '#1e90ff',
     secondary: '#d1e8ff'
   },
   yellow: {
     primary: '#e3bc08',
     secondary: '#fdf1ba'
   }
};
const getColor = (priority: number) => {
  switch (priority) {
    case 1:
    return colors.red;
    case 2:
    return colors.blue;
    default:
    return colors.yellow;
  }
};
@Component({
  selector: 'app-calendar-home',
  template: `
   <mat-card>
   <ng-template #modalContent let-close="close">
  <div class="modal-header">
    <h5 class="modal-title">Event action occurred</h5>
    <button type="button" class="close" (click)="close()">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body">
    <div>
      Action:
      <pre>{{ modalData?.action }}</pre>
    </div>
    <div>
      Event:
      <pre>{{ modalData?.event | json }}</pre>
    </div>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-secondary" (click)="close()">OK</button>
  </div>
</ng-template>
    <div class="toolbar">
      <button mat-icon-button mwlCalendarPreviousView (viewDateChange)="activeDayIsOpen = false"   [view]="view"
      [(viewDate)]="viewDate">
        <mat-icon aria-label="Example icon-button with a heart icon">chevron_left</mat-icon>
      </button>
      <button mat-button>
        {{viewDate|date:'yyyy-MM-dd'}}
      </button>
      <button mat-icon-button mwlCalendarNextView   [view]="view" (viewDateChange)="activeDayIsOpen = false"
      [(viewDate)]="viewDate">
        <mat-icon aria-label="Example icon-button with a heart icon">chevron_right</mat-icon>
      </button>
    </div>
    <ng-container *ngIf="(events$ | async) as calEvents">
      <div [ngSwitch]="view$ | async">
        <mwl-calendar-week-view *ngSwitchCase="'week'"
        [viewDate]="viewDate"
        [events]="calEvents"
        (eventClicked)="handleEvent($event.event)">
        </mwl-calendar-week-view>
        <mwl-calendar-day-view *ngSwitchCase="'day'"
        [viewDate]="viewDate"
        [events]="calEvents"
        (eventClicked)="handleEvent($event.event)">
        </mwl-calendar-day-view>
        <mwl-calendar-month-view *ngSwitchDefault
        [viewDate]="viewDate"
        [events]="calEvents"
        (dayClicked)="dayClicked($event.day)"
        [activeDayIsOpen]="activeDayIsOpen"
        (eventClicked)="handleEvent($event.event)">
        </mwl-calendar-month-view>
      </div>
    </ng-container>
   </mat-card>
  `,
  styles: [`
  :host{
    width:100%;
  }
  .toolbar{
    display:flex;
    flex-direction:row;
  }
  `]
})
export class CalendarHomeComponent implements OnInit {
  viewDate: Date;
  view$: Observable <string>;
  activeDayIsOpen: boolean = true;
  view: CalendarView = CalendarView.Month;
  CalendarView = CalendarView;
  events$: Observable<CalendarEvent[]>;
  @ViewChild('modalContent')
  modalContent: TemplateRef<any>;
  constructor(
    private route: ActivatedRoute,
    private taskService: TaskService,
    private store$: Store<fromRoot.State>
    ) {
    this.viewDate = new Date();
    this.view$ = this.route.paramMap.pipe( map(p => p.get('view')));
    this.events$ = this.store$.pipe(
      select(fromRoot.getAuthState),
      map(auth => auth.user['id']),
      switchMap(userId => this.taskService.getUserTasks(userId)),
      map(tasks => tasks.map(task => ({
        start: startOfDay(task.createDate),
        end: endOfDay(task.dueDate),
        title: task.desc,
        color: getColor(task.priority)
      }))));
      this.events$.subscribe(data => {
        console.log(data);
      });
    }

  ngOnInit() {
  }
  dayClicked({ date, events }: { date: Date; events: CalendarEvent[] }): void {
    if (isSameMonth(date, this.viewDate)) {
      this.viewDate = date;
      if (
        (isSameDay(this.viewDate, date) && this.activeDayIsOpen === true) ||
        events.length === 0
      ) {
        this.activeDayIsOpen = false;
      } else {
        this.activeDayIsOpen = true;
      }
    }
  }
  handleEvent(event): void {
   console.log(event);
  }
}
